package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.IWechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements IWechatService {

    private static final String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber";
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    @Value("${weixin.appid}")
    private String weixinAppid;

    @Value("${weixin.secret}")
    private String weixinSecret;

    /**
     * 获取openid
     *
     * @param code 前端获取的登录凭证
     * @return openid字符串
     */
    @Override
    public String getOpenid(String code) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", weixinAppid);
        paramMap.put("secret", weixinSecret);
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");
        String result = HttpUtil.get(OPENID_URL, paramMap);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //判断成功还是失败
        if (jsonObject.getInt("errcode") ==null||jsonObject.getInt("errcode") == 0) {
            return jsonObject.getStr("openid");
        } else {
            throw new RuntimeException("获取openid失败");
        }
    }
//    @Override
//    public String getOpenid(String code) {
//        Map<String, Object> param = new HashMap<>();
//        param.put("appid", weixinAppid);
//        param.put("secret", weixinSecret);
//        param.put("js_code", code);
//        param.put("grant_type", "authorization_code");
//
//        // 调用正确的OPENID接口
//        String response = HttpUtil.get(OPENID_URL, param);
//        System.out.println("response ============= " + response);
//        JSONObject result = JSONUtil.parseObj(response);
//        System.out.println("result ============================= " + result);
//        // 处理接口响应
//        Integer errCode = result.getInt("errcode");
//        if (errCode != null && errCode != 0) {
//            throw new RuntimeException("获取openid失败: " + errCode + " - " + result.getStr("errmsg"));
//        }
//
//        //提取openid
//        String openid = result.getStr("openid");
//        System.out.println("openid ++++++++++++++++= " + openid);
//        if (openid == null || openid.isEmpty()) {
//            throw new RuntimeException("获取openid失败，返回结果中未包含openid");
//        }
//
//        return openid;
//    }

    /**
     * 获取用户的手机号
     * @param detailCode 前端获取的手机号授权code
     * @return 手机号字符串
     */
    @Override
    public String getPhone(String detailCode) {
        // 检查参数
        if (detailCode == null || detailCode.isEmpty()) {
            throw new IllegalArgumentException("detailCode不能为空");
        }

        // 1. 获取access_token
        String accessToken = getToken();
        if (accessToken == null || accessToken.isEmpty()) {
            throw new RuntimeException("获取access_token失败");
        }

        // 2. 构建请求参数
        JSONObject param = new JSONObject();
        param.set("code", detailCode);

        // 3. 调用手机号接口（正确使用POST方法和URL拼接）
        try (HttpResponse response = HttpRequest.post(PHONE_URL + "?access_token=" + accessToken)
                .body(param.toString())
                .timeout(5000)
                .execute()) {

            String body = response.body();
            JSONObject result = JSONUtil.parseObj(body);

            // 处理错误响应
            Integer errCode = result.getInt("errcode");
            if (errCode != null && errCode != 0) {
                throw new RuntimeException("获取手机号失败: " + errCode + " - " + result.getStr("errmsg"));
            }

            // 正确提取手机号
            JSONObject phoneInfo = result.getJSONObject("phone_info");
            if (phoneInfo == null) {
                throw new RuntimeException("获取手机号失败，返回结果中未包含phone_info");
            }

            String phoneNumber = phoneInfo.getStr("phoneNumber");
            if (phoneNumber == null || phoneNumber.isEmpty()) {
                throw new RuntimeException("获取手机号失败，返回结果中未包含phoneNumber");
            }

            return phoneNumber;
        } catch (Exception e) {
            throw new RuntimeException("获取手机号时发生异常", e);
        }
    }
    /**
     * 获取access_token
     * @return access_token字符串
     */
    public String getToken(){
        Map<String, Object> param = new HashMap<>();
        param.put("grant_type", "client_credential");
        param.put("appid", weixinAppid);
        param.put("secret", weixinSecret);

        String result = HttpUtil.get(TOKEN_URL, param);
        JSONObject parsedObj = JSONUtil.parseObj(result);

        // 处理错误响应
        Integer errCode = parsedObj.getInt("errcode");
        if (errCode != null && errCode != 0) {
            throw new RuntimeException("获取access_token失败: " + errCode + " - " + parsedObj.getStr("errmsg"));
        }

        // 提取access_token
        String accessToken = parsedObj.getStr("access_token");
        if (accessToken == null || accessToken.isEmpty()) {
            throw new RuntimeException("获取access_token失败，返回结果中未包含access_token");
        }

        return accessToken;
    }
}
